import os

import cv2
from PIL import Image


def pic2video0(newvideopath, frames_dir, fps):
    """
        将处理完成的图片合成视频
    :param newvideopath: 生成视频地址
    :param frames_dir: 图片所在文件夹所在文件夹
    :param fps: 每秒图片数
    :return:None
    """
    img = Image.open(f"{frames_dir}/1.jpg")
    w, h = img.size
    # 设置视频编码器,这里使用使用MJPG编码器
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    # 输出视频参数设置,包含视频文件名、编码器、帧率、视频宽高(此处参数需和字符图片大小一致)
    videoWriter = cv2.VideoWriter(newvideopath, fourcc, fps, (w, h))

    order = [int(i.strip(".jpg")) for i in os.listdir(frames_dir) if i.endswith(".jpg")]
    jpglist = [f"{frames_dir}/{i}.jpg" for i in sorted(order)]  # 直接读取可能非顺序帧

    for i, jpg in enumerate(jpglist):
        img = cv2.imread(filename=jpg)
        videoWriter.write(img)
        print(f"将字符画写入视频, 进度{(i + 1)}/{len(jpglist)}！")
    # 视频释放
    videoWriter.release()
    print(f"{newvideopath} 输出完成！")


if __name__ == "__main__":
    pic2video0("fumo/fumo_char.avi", frames_dir="fumo/fumo_char_frames", fps=10)


